package com.ww.springboot.boot.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;

/**
 * 图片转pdf工具类
 *
 * @author wanwei
 */
@Slf4j
public class ImgToPdfUtil {
	public static byte[] toPdf(String url) {
		try {
			return toPdf(Image.getInstance(url));
		} catch (Exception e) {
			log.error("图片转pdf失败", e);
			throw new RuntimeException(e);
		}
	}

	public static byte[] toPdf(byte[] imgb) {
		try {
			return toPdf(Image.getInstance(imgb));
		} catch (Exception e) {
			log.error("图片转pdf失败", e);
			throw new RuntimeException(e);
		}
	}

	public static byte[] toPdf(Image png1) {

		float width = png1.getWidth();
		float height = png1.getHeight();

		Document doc = new Document(new RectangleReadOnly(283, 283), 0, 0, 0, 0);
		if(height/width > 1){
			 doc = new Document(new RectangleReadOnly(283, 425), 0, 0, 0, 0);
		}
		//new一个pdf文档
		try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
			//pdf写入
			PdfWriter.getInstance(doc, outputStream);
			//打开文档
			doc.open();
			//通过文件路径获取image
			png1.setAlignment(Image.MIDDLE);
			// 表示是原来图像的比例;
			png1.scalePercent(283 / png1.getWidth() * 100);
			doc.add(png1);
			doc.close();
			return outputStream.toByteArray();
		} catch (Exception e) {
			log.error("图片转pdf失败", e);
			throw new RuntimeException(e);
		}
	}


	public static byte[] toPdf10X10(byte[] imgb) {
		//new一个pdf文档
		Document doc = new Document(new RectangleReadOnly(283, 283), 0, 0, 0, 0);
		try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
			//pdf写入
			PdfWriter.getInstance(doc, outputStream);
			//打开文档
			doc.open();
			//通过文件路径获取image
			Image png1 = Image.getInstance(imgb);
			png1.setAlignment(Image.MIDDLE);
			// 表示是原来图像的比例;
			png1.scalePercent(283 / png1.getWidth() * 100);
			doc.add(png1);
			doc.close();
			return outputStream.toByteArray();
		} catch (Exception e) {
			log.error("图片转pdf失败", e);
			throw new RuntimeException(e);
		}
	}

}

